package openapi

import (
	"fmt"
	"net/url"
)

type QueryOption struct {
	url.Values
}

type QueryParam func(param *QueryOption)

func NewQueryParam(key, value string) QueryParam {
	return func(param *QueryOption) {
		param.Add(key, value)
	}
}

func NewQueryOption(args ...QueryParam) *QueryOption {
	q := &QueryOption{url.Values{}}
	for _, arg := range args {
		arg(q)
	}
	return q
}

// 生成Url
// @param queryOptions url参数
func GenerateUrl(endpoint, path string, queryParams ...QueryParam) string {
	query := NewQueryOption()
	for _, opt := range queryParams {
		opt(query)
	}
	return GenerateUrlWithOption(endpoint, path, query)
}

// 生成Url
// @param queryOption url参数
func GenerateUrlWithOption(endpoint, path string, queryOption *QueryOption) string {
	if queryOption == nil {
		return fmt.Sprint("https://", endpoint, path)
	}
	var sp string
	if len(queryOption.Values) > 0 {
		sp = "?"
	}
	return fmt.Sprint("https://", endpoint, path, sp, queryOption.Encode())
}
